import axios from 'axios'
import config from './config'
import Cookies from 'js-cookie'
import encryptor from '../utils/encryptor'
import {notification} from 'ant-design-vue'
import command from './command.js'
import router from '@/router'

// 使用vuex做全局loading时使用
// import store from '@/store'

export default function $axios (options) {
  return new Promise((resolve, reject) => {
    const instance = axios.create({
      baseURL: config.baseUrl,
      headers: config.headers,
      timeout: config.timeout,
      withCredentials: config.withCredentials
    })
    var printLog = window.printLog = (s) => {
      if("development" == process.env.NODE_ENV){
        console.log(s);
      }
    }
    var printError = window.printError = (s) => {
      if("development" == process.env.NODE_ENV){
        console.log(s);
      }
    }
    var showErrorMsg = window.showErrorMsg = (s) => {
      notification.error({ message: '出错提示', description: s, duration: 3})
    }
    // request 拦截器
    instance.interceptors.request.use(
      config => {
        let token = Cookies.get('JSESSIONID') || sessionStorage.getItem('JSESSIONID')
        // 1. 请求开始的时候可以结合 vuex 开启全屏 loading 动画
        // console.log(store.state.loading)
        // console.log('准备发送请求...')
        // 2. 带上token
        if (token) {
          config.headers.JSESSIONID = token
          config.headers['X-Access-Token'] = token
        } else {
          // 重定向到登录页面
          // window.location.href="/login.html#/login"
        }
        // 3. 根据请求方法，序列化传来的参数，根据后端需求是否序列化
        if (config.method === 'post') {

        }
        if(config.data && typeof(config.data) === 'object'){
          var dd = config.data;
          if(dd instanceof FormData){
            var data = dd.get("data");
            printLog("request  with file:"+config.url + ","+ data)
            config.data.set("encryptedData", encryptor.encrypt(data))
            config.headers['Content-Type']='multipart/form-data'
          }else{
            var s = JSON.stringify(config.data, null, 2);
            printLog("request:"+config.url);
            printLog(config.data)
            var d = {};
            d.encryptedData = encryptor.encrypt(s);
            config.data = d
          }
        }else{
            var s = config.params ? ","+ JSON.stringify(config.params): "";
            printLog("request:"+ config.url + s);
        }
        return config
      },

      error => {
        // 请求错误时
        console.log('request:', error)
        // 1. 判断请求超时
        if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
          console.log('timeout请求超时')
          // return service.request(originalRequest);// 再重复请求一次
        }
        // 2. 需要重定向到错误页面
        const errorInfo = error.response
        console.log(errorInfo)
        if (errorInfo) {
          error = errorInfo.data // 页面那边catch的时候就能拿到详细的错误信息,看最下边的Promise.reject
          const errorStatus = errorInfo.status // 404 403 500 ...
          // window.location.href="/index.html#/error/${errorStatus}"
        }
        return Promise.reject(error) // 在调用的那边可以拿到(catch)你想返回的错误信息
      }
    )

    // response 拦截器
    instance.interceptors.response.use(
      response => {
        let data
        // IE9时response.data是undefined，因此需要使用response.request.responseText(Stringify后的字符串)
        if (response.data == undefined) {
          data = JSON.parse(response.request.responseText)
        } else {
          data = response.data
        }
        if(data.encryptedData){
          var s = data.encryptedData;
          data.data = encryptor.decrypt(s);
          delete data.encryptedData
        }
        if(data.command && data.command == 'toLogin'){          
          router.push({ path: '/user/adminLogin' })
        }
        printLog("response:")
        printLog(data)
        return data
      },
      err => {
        if (err){
          if(err.response) {
            switch (err.response.status) {
              case 400:
                err.message = '请求错误'
                break
              case 401:
                err.message = '未授权，请登录'
                break
              case 403:
                err.message = '拒绝访问'
                break
              case 404:
                err.message = `请求地址出错: ${err.response.nettyserver.url}`
                break
              case 408:
                err.message = '请求超时'
                break
              case 500:
                err.message = '服务器内部错误'
                break
              case 501:
                err.message = '服务未实现'
                break
              case 502:
                err.message = '网关错误'
                break
              case 503:
                err.message = '服务不可用'
                break
              case 504:
                err.message = '网关超时'
                break
              case 505:
                err.message = 'HTTP版本不受支持'
                break
              default:
            }
          } else if (err.code == 'ECONNABORTED') {
            err.message = '响应超时'
          }else{
            err.message = '访问不到服务器'
          }
        }
        printError(JSON.stringify(err))
        showErrorMsg(err.message)
        return Promise.reject(err) // 返回接口返回的错误信息
      }
    )

    // 请求处理
    instance(options).then(res => {
      if (res.msg) {
        if (res.msg === 'NotLogin') {
          // 重定向到登录页面
          sessionStorage.removeItem('isLogin')
          window.location.href = '/?#/'
          return false
        }
        if (res.ok) {
          if (res.msg && res.msg != '数据为空') {
            toastr.success(res.msg)
          }
        } else {
          if(res.msg){            
            showErrorMsg(res.msg)
          }
        }
        if(res.command){
          if(command[res.command]){            
            command[res.command]()
          }
        }
      }
      resolve(res)
      return false
    }).catch(error => {
      reject(error)
    })
  })
}
